#include "useHead.h"
#include "scriptHead.h"

char ScriptHeader::SCRIPTHEAD[] = {'X', 'A', 'S', 'M'};

void   ScriptHeader::set(int stackSize, int globalDataSize, int mainIndex)
{
	_sh._stackSize = stackSize;
	_sh._mainIndex = mainIndex;
	_sh._globalDataSize = globalDataSize;
}


void ScriptHeader::dump()
{
    puts("\n+++++++++++++++++<Script Head Dump>++++++++++++++++++++++++\n");
	printf("Version : %d.%d\n", major(), minor());
	printf("stack_Size :%d\n", _sh._stackSize);
	printf("global_Data_Size: %d\n", _sh._globalDataSize);
	printf("main_Present : %s\n", _sh._mainIndex < 0 ? "No" : "Yes");
    puts("\n+++++++++++++++++<Script Head Dump>++++++++++++++++++++++++\n");
}


void   ScriptHeader::setVersion(unsigned char min, unsigned char maj)
{
	_sh._version = (((unsigned short)maj) << 8) | min;
}

unsigned char ScriptHeader::minor()
{
	return _sh._version & 0xff;
}

unsigned char ScriptHeader::major()
{
	return (_sh._version >> 8) & 0xff;
}


void   ScriptHeader::writeFile(FILE *fp)
{
	if (fp == NULL)
		return;

	fwrite(SCRIPTHEAD, sizeof(SCRIPTHEAD), 1, fp);
	
	fwrite(&(_sh), sizeof(_sh), 1, fp);  // maybe error!!!!!
}


int ScriptHeader::readFile(FILE *fp)
{
#define FREAD(x, type)  nread = fread(&(x), sizeof(type), 1, fp);\
			if (nread != 1) { \
				fprintf(stderr, "Error! %s %s %d\n", __FILE__, __FUNCTION__, __LINE__); \
				return -1;\
			}
    int nread;
	char buf[32];

	if (fp == NULL)
		return -1;
	
    memset(buf, 0, sizeof(buf));
	FREAD(buf[0], SCRIPTHEAD);
	
	if (strncmp(buf, SCRIPTHEAD, sizeof(SCRIPTHEAD) != 0))
		return -1;

	FREAD(_sh, _sh);
	
	return 0;
}
	
